package com.ruoyi.material.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.basicsystem.domain.ZnDepot;
import com.ruoyi.basicsystem.mapper.ZnDepotMapper;
import com.ruoyi.basicsystem.mapper.ZnSupplierMapper;
import com.ruoyi.bill.domain.ZnDepotItemImportTemplate;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.ZnMaterialCategory;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtil;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.material.domain.*;
import com.ruoyi.material.mapper.ZnMaterialCategoryMapper;
import com.ruoyi.material.mapper.ZnMaterialInitialStockMapper;
import com.ruoyi.material.mapper.ZnUnitMapper;
import com.ruoyi.material.service.IZnMaterialCurrentStockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.material.mapper.ZnMaterialMapper;
import com.ruoyi.material.service.IZnMaterialService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 产品Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-12-24
 */
@Slf4j
@Service
public class ZnMaterialServiceImpl implements IZnMaterialService 
{
    @Autowired
    private ZnMaterialMapper znMaterialMapper;
    @Autowired
    private ZnMaterialInitialStockMapper znMaterialInitialStockMapper;
    @Autowired
    private IZnMaterialCurrentStockService znMaterialCurrentStockService;
    @Autowired
    private ZnUnitMapper znUnitMapper;
    @Autowired
    private ZnMaterialCategoryMapper znMaterialCategoryMapper;
    @Autowired
    private ZnDepotMapper znDepotMapper;
    @Autowired
    private ZnSupplierMapper znSupplierMapper;
    /**
     * 查询产品
     * 
     * @param id 产品主键
     * @return 产品
     */
    @Override
    public ZnMaterial selectZnMaterialById(Long id)
    {
        return znMaterialMapper.selectZnMaterialById(id);
    }

    /**
     * 查询产品列表
     * 
     * @param znMaterial 产品
     * @return 产品
     */
    @Override
    @DataScope(deptAlias = "zn_material", userAlias = "zn_material")
    public List<ZnMaterial> selectZnMaterialList(ZnMaterial znMaterial)
    {
        znMaterial.setTenantId(SecurityUtils.getLoginUser().getUser().getTenantId());
        znMaterial.setDeleteFlag("0");
        List<ZnMaterial> list=  znMaterialMapper.selectZnMaterialList(znMaterial);
       /* for(ZnMaterial zn:list){
            if( zn.getZnMaterialExtendList()!=null&&zn.getZnMaterialExtendList().size()>0){
                ZnMaterialExtend znMaterialExtend= zn.getZnMaterialExtendList().get(0);
                zn.setBarCode(znMaterialExtend.getBarCode());
            }
        }*/
        return list;
    }

    /**
     * 新增产品
     * 
     * @param znMaterial 产品
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertZnMaterial(ZnMaterial znMaterial)
    {
        int isname=this.checkMaterNameIsEx(znMaterial);
        if(isname>0){
            return AjaxResult.error("名称重复");
        }
        if(znMaterial.getChineseChar()!=null){
            znMaterial.setChineseChar(znMaterial.getChineseChar().toUpperCase());
        }else{
            return AjaxResult.error("首字母不能为空");
        }
        ZnDepot znDepot = new ZnDepot();
        znDepot.setTenantId(SecurityUtils.getTenantId());
        znDepot.setDeleteFlag("0");
        List<ZnDepot> deptList = znDepotMapper.selectZnDepotList(znDepot);
        if(deptList.size()==0 || deptList ==null){
            throw  new RuntimeException("请先创建仓库，在新增产品");
        }
        SysUser sysUser=SecurityUtils.getLoginUser().getUser();
        znMaterial.setTenantId(sysUser.getTenantId());
        znMaterial.setEnabled(1);//0禁用 1启用
        znMaterial.setDeptId(sysUser.getDeptId());
        znMaterial.setUserId(sysUser.getUserId());
        int rows = znMaterialMapper.insertZnMaterial(znMaterial);
        for(ZnMaterialExtend ex:znMaterial.getZnMaterialExtendList()){
            ex.setTenantId(znMaterial.getTenantId());
        }
        insertZnMaterialExtend(znMaterial);
        List<ZnMaterialInitialStock>  znMaterialInitialStocks=  znMaterial.getZnMaterialInitialStocks();
        List<ZnMaterialCurrentStock> znMaterialCurrentStocks=new ArrayList<>();
        if(znMaterialInitialStocks!=null){
            for(ZnMaterialInitialStock znMaterialInitialStock:znMaterialInitialStocks){
                /**
                 * 当前库存
                 */
                ZnMaterialCurrentStock znMaterialCurrentStock=new ZnMaterialCurrentStock();
                znMaterialCurrentStock.setCurrentNumber(znMaterialInitialStock.getNumber());
                znMaterialCurrentStock.setDeleteFlag("0");
                znMaterialCurrentStock.setDepotId(znMaterialInitialStock.getDepotId());
                znMaterialCurrentStock.setMaterialId(znMaterial.getId());
                znMaterialCurrentStock.setTenantId(sysUser.getTenantId());
                znMaterialCurrentStocks.add(znMaterialCurrentStock);
                /**
                 * 初始库存
                 */
                boolean f=false;
                if(znMaterialInitialStock.getNumber()!=null&&znMaterialInitialStock.getNumber().longValue()>0){//库存大于零在插入
                    f=true;
                }else if(znMaterialInitialStock.getLowSafeStock()!=null&&znMaterialInitialStock.getLowSafeStock().longValue()>0){//库存大于零在插入
                    f=true;
                }else if(znMaterialInitialStock.getHighSafeStock()!=null&&znMaterialInitialStock.getHighSafeStock().longValue()>0){//库存大于零在插入
                    f=true;
                }
                if(f){
                    znMaterialInitialStock.setMaterialId(znMaterial.getId());
                    SysUser user=SecurityUtils.getLoginUser().getUser();
                    znMaterialInitialStock.setTenantId(user.getTenantId());
                    znMaterialInitialStockMapper.insertZnMaterialInitialStock(znMaterialInitialStock);
                    /* ZnMaterialInitialStock ZnMaterialInitialStockQuery=new ZnMaterialInitialStock();
                    ZnMaterialInitialStockQuery.setMaterialId(znMaterial.getId());
                    ZnMaterialInitialStockQuery.setTenantId(user.getTenantId());
                    ZnMaterialInitialStockQuery.setDepotId(znMaterialInitialStock.getDepotId());
                   List<ZnMaterialInitialStock> lists=znMaterialInitialStockMapper.selectZnMaterialInitialStockList(ZnMaterialInitialStockQuery);
                    if(lists.size()>0){//执行更新
                        ZnMaterialInitialStock zupdate=lists.get(0);
                        zupdate.setHighSafeStock(znMaterialInitialStock.getHighSafeStock());
                        zupdate.setNumber(znMaterialInitialStock.getNumber());
                        zupdate.setLowSafeStock(znMaterialInitialStock.getLowSafeStock());
                        znMaterialInitialStockMapper.updateZnMaterialInitialStock(zupdate);
                    }else{

                    }*/
                }

            }
            if(znMaterialCurrentStocks.size()>0){
                znMaterialCurrentStockService.batchznMaterialCurrentStocks(znMaterialCurrentStocks);
            }
        }else{//没有初始化库存记录为空的是，也记录每个仓库的初始化记录

            ZnMaterialInitialStock znMaterialInitialStock = new ZnMaterialInitialStock();
            for (ZnDepot depot:deptList) {
                znMaterialInitialStock=new ZnMaterialInitialStock();
                znMaterialInitialStock.setNumber(BigDecimal.ZERO);
                znMaterialInitialStock.setDeleteFlag("0");
                znMaterialInitialStock.setDepotId(depot.getId());
                znMaterialInitialStock.setMaterialId(znMaterial.getId());
                znMaterialInitialStock.setTenantId(sysUser.getTenantId());
                znMaterialInitialStockMapper.insertZnMaterialInitialStock(znMaterialInitialStock);
                /**
                 * 当前库存
                 */
                ZnMaterialCurrentStock znMaterialCurrentStock=new ZnMaterialCurrentStock();
                znMaterialCurrentStock.setCurrentNumber(znMaterialInitialStock.getNumber());
                znMaterialCurrentStock.setDeleteFlag("0");
                znMaterialCurrentStock.setDepotId(znMaterialInitialStock.getDepotId());
                znMaterialCurrentStock.setMaterialId(znMaterial.getId());
                znMaterialCurrentStock.setTenantId(sysUser.getTenantId());
                znMaterialCurrentStocks.add(znMaterialCurrentStock);

                if(znMaterialCurrentStocks.size()>0){
                    znMaterialCurrentStockService.batchznMaterialCurrentStocks(znMaterialCurrentStocks);
                }
            }
        }
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 检查名称是否存在
     * @param znMaterial
     * @return
     */
    @Override
    public int checkMaterNameIsEx(ZnMaterial znMaterial) {
        znMaterial.setTenantId(SecurityUtils.getTenantId());
        return znMaterialMapper.checkMaterNameIsEx(znMaterial).intValue();
    }

    @Override
    public List<ZnMaterial> selectZnMaterialAllList(ZnMaterial znMaterial) {
        znMaterial.setTenantId(SecurityUtils.getTenantId());
        znMaterial.setDeleteFlag("0");
        return znMaterialMapper.selectZnMaterialAllList(znMaterial);
    }

    /**
     * 导入商品 （目前使用）
     * @param list
     * @param updateSupport
     * @param operName
     * @return
     */
    @Override
    @Transactional
    public String importMaterialList(List<ZnMaterial> list, boolean updateSupport, String operName) {
        int successNum = 0;
        int failureNum = 0;
        int repeatNum = 0;
        int index = 1;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        StringBuilder repeatMsg = new StringBuilder();
        Date now = new Date();
        List<ZnMaterial> importList = new ArrayList<>();
        try
        {
            //单位，类别，仓库
//            ZnUnit znUnit = new ZnUnit();
//            znUnit.setTenantId(SecurityUtils.getTenantId());
//            znUnit.setDeleteFlag("0");
//            List<ZnUnit> unitList = znUnitMapper.selectZnUnitList(znUnit);
            ZnMaterialCategory znMaterialCategory = new ZnMaterialCategory();
            znMaterialCategory.setDeleteFlag("0");
            znMaterialCategory.setTenantId(SecurityUtils.getTenantId());
            List<ZnMaterialCategory> znMaterialCategoryList = znMaterialCategoryMapper.selectZnMaterialCategoryList(znMaterialCategory);
            ZnDepot znDepot = new ZnDepot();
            znDepot.setTenantId(SecurityUtils.getTenantId());
            znDepot.setDeleteFlag("0");
            List<ZnDepot> deptList = znDepotMapper.selectZnDepotList(znDepot);

//            Map<String,Long> unitMap = null;
//            for (ZnUnit unit:unitList) {
//                unitMap.put(unit.getBasicUnit()+"_"+unit.getOtherUnit()+"_"+unit.getRatio(),unit.getId());
//                if(StringUtils.isNotBlank(unit.getOtherUnitTwo())){
//                    unitMap.put(unit.getBasicUnit()+"_"+unit.getOtherUnitTwo()+"_"+unit.getRatioTwo(),unit.getId());
//                }
//                if(StringUtils.isNotBlank(unit.getOtherUnitThree())){
//                    unitMap.put(unit.getBasicUnit()+"_"+unit.getOtherUnitThree()+"_"+unit.getRatioThree(),unit.getId());
//                }
//            }
            Map<String,Long> materialCategoryMap =null;
            for (ZnMaterialCategory materialCategory:znMaterialCategoryList) {
                materialCategoryMap.put(materialCategory.getName().trim(),materialCategory.getId());
            }
            Map<String,Long> znDepotMap =null;
            for (ZnDepot depot:deptList) {
                znDepotMap.put(depot.getName(),depot.getId());
            }
            HashSet<String> barCodeSet =  null;
            HashSet<Long> depotIdSet =  new HashSet();
            HashSet waitSet = new HashSet();//待入库
            if(barCodeSet==null){
                barCodeSet = new HashSet<>();
                ZnMaterial ZnMaterial = new ZnMaterial();
                ZnMaterial.setTenantId(SecurityUtils.getTenantId());
                ZnMaterial.setDeleteFlag("0");
                List<ZnMaterial> tempList = znMaterialMapper.selectZnMaterialList(ZnMaterial);
                for (ZnMaterial temp:tempList) {
                    barCodeSet.add(temp.getBarCode());
                }
            }

            for (ZnMaterial material : list)
            {
                if(StringUtils.isEmpty(material.getName()) || StringUtils.isEmpty(material.getUnit()) || StringUtils.isEmpty(material.getBarCode()) ){
                    failureNum++;
                    String msg = failureNum + "、第"+index+"行，";
                    if(StringUtils.isEmpty(material.getName())){
                        msg += "名称、";
                    }
                    if(StringUtils.isEmpty(material.getBarCode())){
                        msg += "条码、";
                    }
                    if(StringUtils.isEmpty(material.getUnit())){
                        msg += "单位";
                    }
                    if(msg.endsWith("、")){
                        msg =  msg.substring(0,msg.length()-1)+"为必填项，不能为空";
                    }
                    failureMsg.append("<br/>" + msg);
                }else{//条码不能为空,并使用条码作为唯一的识别key
//                    System.out.println(JSON.toJSONString(barCodeSet));
                    if (!barCodeSet.contains(material.getBarCode()))
                    {
                        material.setCreateBy(SecurityUtils.getUsername());
                        material.setTenantId(SecurityUtils.getTenantId());
                        material.setDeptId(SecurityUtils.getDeptId());
                        material.setUserId(SecurityUtils.getUserId());
                        material.setDeleteFlag("0");
                        material.setEnabled(0);
                        material.setCreateTime(now);
                        waitSet.add(material.getBarCode());
                        Long categoryId = null;
                        if(!materialCategoryMap.containsKey(material.getCategoryName().trim())){
                            znMaterialCategory.setName(material.getCategoryName().trim());
                            znMaterialCategory.setCreateTime(new Date());
                            znMaterialCategory.setParentId(0l);
                            znMaterialCategory.setSort("0");
                            znMaterialCategoryMapper.insertZnMaterialCategory(znMaterialCategory);
                            materialCategoryMap.put(material.getCategoryName().trim(),znMaterialCategory.getId());
                            categoryId = znMaterialCategory.getId();
                        }else{
                            categoryId =  materialCategoryMap.get(material.getCategoryName().trim());
                        }
                        material.setCategoryId(categoryId);
                        material.setChineseChar(StringUtil.getPinYinHeadChar(material.getName().trim()));
                        importList.add(material);
                        successNum++;
                    }else{
                        repeatNum++;
                        failureMsg.append("<br/>" + repeatNum + "、第"+index+"行，条码：（" + material.getBarCode() + "） 已存在");
                    }
                }
                index++;
            }
            if(importList.size()>0){
                //java8 去重条码相同
                log.debug("第一次去重前数量："+importList.size());
                importList = importList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ZnMaterial::getBarCode))),ArrayList::new));
                log.debug("第一次去重后数量："+importList.size());
                log.debug("待导入数量："+importList.size());

                ZnMaterialExtend materialExtend = null;
                List<ZnMaterialExtend> extendList = null;
                for (ZnMaterial material:importList) {
                    znMaterialMapper.insertZnMaterial(material);
                    materialExtend = new ZnMaterialExtend();
                    extendList = new ArrayList<>();
                    BeanUtils.copyBeanProp(materialExtend,material);
                    materialExtend.setId(null);
                    materialExtend.setMaterialId(material.getId());
                    materialExtend.setCommodityUnit(material.getUnit());
                    materialExtend.setDefaultFlag("1");
                    extendList.add(materialExtend);
//                    System.out.println(JSON.toJSONString(extendList));
                    znMaterialMapper.batchZnMaterialExtend(extendList);

                    List<ZnMaterialCurrentStock> znMaterialCurrentStocks=new ArrayList<>();
                    /**
                     * 当前库存
                     */
                    for (Long deptId:depotIdSet) {
                        ZnMaterialCurrentStock znMaterialCurrentStock=new ZnMaterialCurrentStock();
                        znMaterialCurrentStock.setCurrentNumber(new BigDecimal(0));
                        znMaterialCurrentStock.setDeleteFlag("0");
                        znMaterialCurrentStock.setDepotId(deptId);
                        znMaterialCurrentStock.setMaterialId(material.getId());
                        znMaterialCurrentStock.setTenantId(SecurityUtils.getTenantId());
                        znMaterialCurrentStocks.add(znMaterialCurrentStock);
                    }
                    if(znMaterialCurrentStocks.size()>0){
                        znMaterialCurrentStockService.batchznMaterialCurrentStocks(znMaterialCurrentStocks);
                    }
                }
            }
            if (failureNum > 0 || repeatNum > 0)
            {
                String  msg = "";
                if(successNum>0){
                    msg ="已成功导入数据，共 " + successNum + " 条；";
                }
                msg  += "导入失败数据，共 "+ (failureNum+repeatNum)+" 条，其中， ";
                if (failureNum > 0)
                {
                    msg +=" 数据不完整 " + failureNum + " 条，";
                }
                if (repeatNum > 0)
                {
                    msg +=" 数据已存在 " + repeatNum + " 条，";
                }
                msg += "错误如下：";
                failureMsg.insert(0, msg);
                return repeatMsg.toString()+failureMsg.toString();
            }
            else
            {
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条。");
            }
        }catch (Exception e){
            failureNum++;
            String msg = "<br/>" + failureNum + "、第"+index+"行，导入异常。";
            failureMsg.append(msg + e.getMessage());
            e.printStackTrace();
        }
        return successMsg.toString();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult analysisMaterialList(List<ZnDepotItemImportTemplate> list) {
        int successNum = 0;
        int failureNum = 0;
        int repeatNum = 0;
        int index = 1;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        StringBuilder repeatMsg = new StringBuilder();
        Date now = new Date();
        List<ZnMaterial> importList = new ArrayList<>();
        try
        {
            //单位，类别
            ZnUnit znUnit = new ZnUnit();
            znUnit.setTenantId(SecurityUtils.getTenantId());
            znUnit.setDeleteFlag("0");
            List<ZnUnit> unitList = znUnitMapper.selectZnUnitList(znUnit);
            ZnMaterialCategory znMaterialCategory = new ZnMaterialCategory();
            znMaterialCategory.setDeleteFlag("0");
            znMaterialCategory.setTenantId(SecurityUtils.getTenantId());
            List<ZnMaterialCategory> znMaterialCategoryList = znMaterialCategoryMapper.selectZnMaterialCategoryList(znMaterialCategory);
            Map<String,Long> unitMap = new HashMap<>();
            for (ZnUnit unit:unitList) {
                if(StringUtils.isNotBlank(unit.getOtherUnit())){
                    unitMap.put(unit.getBasicUnit()+"_"+unit.getOtherUnit()+"_"+unit.getRatio(),unit.getId());
                }
                if(StringUtils.isNotBlank(unit.getOtherUnitTwo())){
                    unitMap.put(unit.getBasicUnit()+"_"+unit.getOtherUnitTwo()+"_"+unit.getRatioTwo(),unit.getId());
                }
                if(StringUtils.isNotBlank(unit.getOtherUnitThree())){
                    unitMap.put(unit.getBasicUnit()+"_"+unit.getOtherUnitThree()+"_"+unit.getRatioThree(),unit.getId());
                }
            }
            Map<String,Long> materialCategoryMap =new HashMap<>();
            for (ZnMaterialCategory materialCategory:znMaterialCategoryList) {
                materialCategoryMap.put(materialCategory.getName().trim(),materialCategory.getId());
            }
            HashSet waitSet = new HashSet();//待入库

            ZnMaterial ZnMaterial = new ZnMaterial();
            ZnMaterial.setTenantId(SecurityUtils.getTenantId());
            ZnMaterial.setDeleteFlag("0");
            List<ZnMaterial> tempList = znMaterialMapper.selectZnMaterialSelectList(ZnMaterial);
            List<ZnDepotItemImportTemplate> tempImportList = new ArrayList<>();
            List<ZnMaterial> resultList = new ArrayList<>();
            for (ZnDepotItemImportTemplate material : list)
            {
                if(StringUtils.isEmpty(material.getName()) || StringUtils.isEmpty(material.getUnit()) || StringUtils.isEmpty(material.getMaterialCategoryName()) ){
                    failureNum++;
                    String msg = failureNum + "、第"+index+"行，";
                    if(StringUtils.isEmpty(material.getName())){
                        msg += "商品名称、";
                    }
                    if(StringUtils.isEmpty(material.getMaterialCategoryName())){
                        msg += "商品类别、";
                    }
                    if(StringUtils.isEmpty(material.getUnit())){
                        msg += "单位";
                    }
                    if(msg.endsWith("、")){
                        msg =  msg.substring(0,msg.length()-1)+"为必填项，不能为空";
                    }
                    failureMsg.append("<br/>" + msg);
                    System.out.println(msg);
                }else{
                        boolean isOk = false;
                        for (ZnMaterial znMaterial:tempList) {
                            if(material.getName().trim().equals(znMaterial.getName()) && material.getMaterialCategoryName().trim().equals(znMaterial.getCategoryName()) && material.getUnit().trim().equals(znMaterial.getUnit())){
                                znMaterial.setOperNumber(material.getOperNumber());
                                znMaterial.setRemark(material.getRemark());
                                resultList.add(znMaterial);
                                successNum++;
                                isOk = true;
                                break;
                            }
                        }
                        if(!isOk){
                            repeatNum++;
                            failureMsg.append("<br/>" + repeatNum + "、第"+index+"行，商品：（" + material.getName() + "） 匹配不存在");
                        }
                }
                index++;
            }

            if (failureNum > 0 || repeatNum > 0)
            {
                String  msg = "";
                msg  += "导入失败数据，共 "+ (failureNum+repeatNum)+" 条，其中， ";
                if (failureNum > 0)
                {
                    msg +=" 数据不完整 " + failureNum + " 条，";
                }
                if (repeatNum > 0)
                {
                    msg +=" 匹配不存在 " + repeatNum + " 条，";
                }
                msg += "错误如下：";
                failureMsg.insert(0, msg);
                return AjaxResult.error(failureMsg.toString()+repeatMsg.toString());
            }
            else
            {
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条。");
                return AjaxResult.success(successMsg.toString(),resultList);
            }
        }catch (Exception e){
            failureNum++;
            String msg = "<br/>" + failureNum + "、第"+index+"行，导入异常。";
            failureMsg.append(msg + e.getMessage());
            e.printStackTrace();
        }
        return AjaxResult.success("导入完成");
    }

    /**
     * 导入文件
     * @param file
     * @param updateSupport
     * @param operName
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importMaterial(MultipartFile file, boolean updateSupport, String operName) {
        //单位，类别，仓库
        ZnUnit znUnit = new ZnUnit();
        znUnit.setTenantId(SecurityUtils.getTenantId());
        znUnit.setDeleteFlag("0");
        List<ZnUnit> unitList = znUnitMapper.selectZnUnitList(znUnit);
        ZnMaterialCategory ZnMaterialCategory = new ZnMaterialCategory();
        ZnMaterialCategory.setDeleteFlag("0");
        ZnMaterialCategory.setTenantId(SecurityUtils.getTenantId());
        List<ZnMaterialCategory> znMaterialCategoryList = znMaterialCategoryMapper.selectZnMaterialCategoryList(ZnMaterialCategory);
        ZnDepot znDepot = new ZnDepot();
        znDepot.setTenantId(SecurityUtils.getTenantId());
        znDepot.setDeleteFlag("0");
        List<ZnDepot> deptList = znDepotMapper.selectZnDepotList(znDepot);

        Map<String,Long> unitMap = null;
        for (ZnUnit unit:unitList) {
            unitMap.put(unit.getBasicUnit()+"_"+unit.getOtherUnit()+"_"+unit.getRatio(),unit.getId());
            if(StringUtils.isNotBlank(unit.getOtherUnitTwo())){
                unitMap.put(unit.getBasicUnit()+"_"+unit.getOtherUnitTwo()+"_"+unit.getRatioTwo(),unit.getId());
            }
            if(StringUtils.isNotBlank(unit.getOtherUnitThree())){
                unitMap.put(unit.getBasicUnit()+"_"+unit.getOtherUnitThree()+"_"+unit.getRatioThree(),unit.getId());
            }
        }
        Map<String,Long> materialCategoryMap =null;
        for (ZnMaterialCategory materialCategory:znMaterialCategoryList) {
            materialCategoryMap.put(materialCategory.getName(),materialCategory.getId());
        }
        Map<String,Long> znDepotMap =null;
        for (ZnDepot depot:deptList) {
            znDepotMap.put(depot.getName(),depot.getId());
        }
        HashSet<String> barCodeSet = null;
        HashSet waitList = new HashSet();//待入库
        if(barCodeSet==null){
            barCodeSet = new HashSet<>();
            ZnMaterial ZnMaterial = new ZnMaterial();
            ZnMaterial.setTenantId(SecurityUtils.getTenantId());
            ZnMaterial.setDeleteFlag("0");
            List<ZnMaterial> tempList = znMaterialMapper.selectZnMaterialList(ZnMaterial);
            for (ZnMaterial temp:tempList) {
                barCodeSet.add(temp.getBarCode());
            }
        }
        int successNum = 0;
        int failureNum = 0;
        int repeatNum = 0;
        int index = 1;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        StringBuilder repeatMsg = new StringBuilder();
        Date now = new Date();
        try
        {
            List<ZnMaterial> importList = new ArrayList<>();
            Workbook wb =  new HSSFWorkbook(file.getInputStream());
            Sheet sheet = wb.getSheetAt(0);
            //标题行
            Row titleRow= sheet.getRow(0);
            if(titleRow.getCell(0).getStringCellValue().contains("名称") && titleRow.getCell(1).getStringCellValue().contains("规格") && titleRow.getCell(2).getStringCellValue().contains("型号") && titleRow.getCell(3).getStringCellValue().contains("颜色")  && titleRow.getCell(4).getStringCellValue().contains("类别") && titleRow.getCell(5).getStringCellValue().contains("保质期")
                    && titleRow.getCell(6).getStringCellValue().contains("基本单位") && titleRow.getCell(7).getStringCellValue().contains("副单位")  && titleRow.getCell(8).getStringCellValue().contains("条码")  && titleRow.getCell(9).getStringCellValue().contains("副条码")  && titleRow.getCell(10).getStringCellValue().contains("比例") && titleRow.getCell(11).getStringCellValue().contains("采购价") && titleRow.getCell(12).getStringCellValue().contains("零售价") && titleRow.getCell(13).getStringCellValue().contains("销售价") && titleRow.getCell(14).getStringCellValue().contains("最低售价")) {
                //遍历行 从下标第一行开始（去除标题）
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (!ExcelUtil.isRowEmptyStatic(row)) {
                        String name = row.getCell(0).getStringCellValue().trim();
                        String materialCategory = row.getCell(4).getStringCellValue().trim();
                        String expiryNum = row.getCell(5).getStringCellValue().trim();
                        String unit = row.getCell(6).getStringCellValue().trim();
                        String unitSub = row.getCell(7).getStringCellValue().trim();
                        String barCode = row.getCell(8).getStringCellValue().trim();
                        String barCode1 = row.getCell(9).getStringCellValue().trim();
                        String ratio = row.getCell(10).getStringCellValue().trim();
                        String unitAll =  unit +"_"+unitSub+"_"+ratio;
                        Long unitId = null;
                        boolean isMulUnit = false;
                        boolean mulUnitTrue = true;
                        if(StringUtils.isNotBlank(unitSub) || StringUtils.isNotBlank(ratio) || StringUtils.isNotBlank(barCode1) ){
                            isMulUnit = true;
                        }

                        if(StringUtils.isNotBlank(unitSub) && StringUtils.isNumeric(ratio) ){
                            if(unitMap.containsKey(unitAll)){
                                unitId = unitMap.get(unitAll);
                            }else{
                                mulUnitTrue = false;
                            }
                        }
                        if(StringUtils.isEmpty(name) || StringUtils.isEmpty(unit) || StringUtils.isEmpty(barCode) || !materialCategoryMap.containsKey(materialCategory) || !StringUtils.isNumeric(expiryNum) || (isMulUnit && !StringUtils.isNotBlank(barCode1)) || (isMulUnit && !StringUtils.isNumeric(ratio)) || (isMulUnit && mulUnitTrue && unitId!=null)) {
                            failureNum++;
                            String msg = failureNum + "、第" + index + "行，";
                            if (StringUtils.isEmpty(name)) {
                                msg += "名称、";
                            }
                            if (StringUtils.isEmpty(unit)) {
                                msg += "单位、";
                            }
                            if (StringUtils.isEmpty(barCode)) {
                                msg += "条码";
                            }
                            if (msg.endsWith("、")) {
                                msg = msg.substring(0, msg.length() - 1) + "为必填项不能为空";
                            }
                            if (!materialCategoryMap.containsKey(materialCategory)) {
                                msg += (msg.length()>0?";":"") +"类别（"+materialCategory+")数据库不存在；";
                            }
                            if(!StringUtils.isNumeric(expiryNum)){
                                msg += (msg.length()>0?";":"") +"保质期只能为数字；";
                            }
                            if(isMulUnit && !StringUtils.isNotBlank(barCode1)){
                                msg += (msg.length()>0?";":"") +"副标题不能为空；";
                            }
                            if(isMulUnit && !StringUtils.isNumeric(ratio)){
                                msg += (msg.length()>0?";":"") +"比例只能为数字；";
                            }
                            if (isMulUnit && mulUnitTrue && unitId!=null){
                                msg += (msg.length()>0?";":"") +"基本单位（"+unit+")"+"副单位（"+unitSub+")"+"比例（"+ratio+")不存在";
                            }
                            if (msg.endsWith("；")) {
                                msg = msg.substring(0, msg.length() - 1) + "。";
                            }
                            failureMsg.append("<br/>" + msg);
                        }else{
                            ZnMaterial material = new ZnMaterial();
                            material.setEnabled(0);
                            material.setDeleteFlag("0");
                            material.setTenantId(SecurityUtils.getTenantId());
                            material.setUserId(SecurityUtils.getUserId());
                            material.setDeptId(SecurityUtils.getDeptId());
                            material.setName(name);
                            material.setStandard(row.getCell(1).getStringCellValue().trim());
                            material.setModel(row.getCell(2).getStringCellValue().trim());
                            material.setColor(row.getCell(3).getStringCellValue().trim());
                            material.setCategoryId(materialCategoryMap.get(materialCategory));
                            material.setExpiryNum(Integer.valueOf(expiryNum));
                            if(isMulUnit && unitId!=null){
                                material.setUnitId(unitId);
                            }else{
                                material.setUnit(unit);
                            }

                        }

                    }
                }
                //TODO 下面业务尚未修改
//                for (ZnMaterial material : list)
//                {
//                    if(StringUtils.isEmpty(material.getName()) || StringUtils.isEmpty(material.getUnit()) || StringUtils.isEmpty(material.getBarCode()) || ){
//                        failureNum++;
//                        String msg = failureNum + "、第"+index+"行，";
//                        if(StringUtils.isEmpty(material.getName())){
//                            msg += "名称、";
//                        }
//                        if(StringUtils.isEmpty(material.getBarCode())){
//                            msg += "条码、";
//                        }
//                        if(StringUtils.isEmpty(material.getUnit())){
//                            msg += "单位";
//                        }
//                        if(msg.endsWith("、")){
//                            msg =  msg.substring(0,msg.length()-1)+"为必填项，不能为空";
//                        }
//                        failureMsg.append("<br/>" + msg);
//                    }else{//姓名、身份证不能为空,并使用身份证作为唯一的识别key
//                        if (!barCodeSet.contains(material.getBarCode()))
//                        {
//                            material.setCreateBy(SecurityUtils.getUsername());
//                            material.setTenantId(SecurityUtils.getTenantId());
//                            material.setDeptId(SecurityUtils.getDeptId());
//                            material.setUserId(SecurityUtils.getUserId());
//                            material.setDeleteFlag("0");
//                            material.setEnabled(0);
//                            material.setCreateTime(now);
//                            waitList.add(material.getBarCode());
//                            importList.add(material);
//                            successNum++;
//                        }else{
//                            repeatNum++;
//                            failureMsg.append("<br/>" + repeatNum + "、第"+index+"行，用户（身份证号：" + material.getBarCode() + "） 已存在");
//                        }
//                    }
//                    index++;
//                }
                if(importList.size()>0){
                    //java8 去重条码相同
                    log.debug("第一次去重前数量："+importList.size());
                    importList = importList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ZnMaterial::getBarCode))),ArrayList::new));
                    log.debug("第一次去重后数量："+importList.size());
                    log.debug("待导入数量："+importList.size());
//                int pageSize = 800;
//                if(importList.size()>pageSize){
//                    int pageNum = importList.size()/pageSize ;
//                    log.debug("本次导入数量："+importList.size());
//                    pageNum = (importList.size()> pageNum*pageSize)?(pageNum+1) : pageNum;
//                    log.debug("导入次数："+pageNum);
//                    int i = 1;
//                    while(i<=pageNum){
//                        log.debug("页数："+i+"。"+(i-1)*pageSize +"-"+ (i==pageNum?importList.size():i*pageSize));
//                        znMaterialMapper.batchInsertMaterial(importList.subList((i-1)*pageSize,(i==pageNum?importList.size():i*pageSize)));
//                        i++;
//                    }
//                }else if(importList.size()>0){
//                    znMaterialMapper.batchInsertMaterial(importList);
//                }
                    ZnMaterialExtend materialExtend = null;
                    List<ZnMaterialExtend> extendList = null;
                    for (ZnMaterial material:importList) {
                        znMaterialMapper.insertZnMaterial(material);
                        materialExtend = new ZnMaterialExtend();
                        extendList = new ArrayList<>();
                        BeanUtils.copyBeanProp(materialExtend,material);
                        materialExtend.setCommodityUnit(material.getUnit());
                        materialExtend.setMaterialId(material.getId());
                        materialExtend.setDefaultFlag("1");
                        extendList.add(materialExtend);
                        znMaterialMapper.batchZnMaterialExtend(extendList);

                    }
                }
                if (failureNum > 0 || repeatNum > 0)
                {
                    String  msg = "";
                    if(successNum>0){
                        msg ="已成功导入数据，共 " + successNum + " 条；";
                    }
                    msg  += "导入失败数据，共 "+ (failureNum+repeatNum)+" 条，其中， ";
                    if (failureNum > 0)
                    {
                        msg +=" 数据不完整 " + failureNum + " 条，";
                    }
                    if (repeatNum > 0)
                    {
                        msg +=" 数据已存在 " + repeatNum + " 条，";
                    }
                    msg += "错误如下：";
                    failureMsg.insert(0, msg);
                    return repeatMsg.toString()+failureMsg.toString();
                }
                else
                {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
            }else{
                throw new ServiceException("导入文件格式不正常，请按照模板导入");
            }
        }
        catch (Exception e)
        {
            failureNum++;
            String msg = "<br/>" + failureNum + "、第"+index+"行，导入异常。";
            failureMsg.append(msg + e.getMessage());
            e.printStackTrace();
        }
        return successMsg.toString();
    }

    /**
     * 修改产品
     * 
     * @param znMaterial 产品
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateZnMaterial(ZnMaterial znMaterial)
    {
        int isname=this.checkMaterNameIsEx(znMaterial);
        if(isname>0){
            return AjaxResult.error("名称重复");
        }
        if(znMaterial.getChineseChar()!=null){
            znMaterial.setChineseChar(znMaterial.getChineseChar().toUpperCase());
        }else{
            return AjaxResult.error("首字母不能为空");
        }
        ZnMaterial temp= znMaterialMapper.selectZnMaterialAllById(znMaterial.getId());
        if(!temp.getTenantId().equals(SecurityUtils.getLoginUser().getUser().getTenantId())){
            return AjaxResult.error("不属于您的数据");
        }
        List<ZnMaterialExtend> znMaterialExtendList = znMaterial.getZnMaterialExtendList();
        List<ZnMaterialExtend> znMaterialExtendUpdate=new ArrayList<>();
        List<ZnMaterialExtend> znMaterialExtendInsert=new ArrayList<>();
        /**
         * 当前库存
         */
        List<ZnMaterialCurrentStock> znMaterialCurrentStocksInsert=new ArrayList<>();
        List<Long> oldExtendIds = new ArrayList<>();
        for (ZnMaterialExtend extend :temp.getZnMaterialExtendList()){
            oldExtendIds.add(extend.getId());

        }
        System.out.println(oldExtendIds);
        if(znMaterial.getUnitId() !=null){//多单位
            ZnUnit znUnit = znUnitMapper.selectZnUnitById(znMaterial.getUnitId());
            for(ZnMaterialExtend znMaterialExtend:znMaterialExtendList) {
                boolean isPrice = true;
                //商品采购价格为空的时候，期初库存中，如果有期初价格并且大于0的时候,就把第一个期初价格作为商品的采购价
                if(znMaterialExtend.getPurchaseDecimal()==null && znMaterial.getZnMaterialInitialStocks().size()>0){
                    for (ZnMaterialInitialStock znMaterialInitialStock:znMaterial.getZnMaterialInitialStocks()) {
                        if(znMaterialInitialStock.getPrice()!=null && znMaterialInitialStock.getPrice().longValue()>0 && isPrice){
                            znMaterialExtend.setPurchaseDecimal(znMaterialInitialStock.getPrice());
                            isPrice = false;
                        }
                    }
                }
                znMaterialExtend.setMaterialId(temp.getId());
                znMaterialExtend.setTenantId(znMaterial.getTenantId());
                znMaterialExtend.setDeleteFlag("0");
                if(znMaterialExtend.getCommodityUnit().equals(znUnit.getBasicUnit())){
                    znMaterialExtend.setDefaultFlag("1");
                }else{
                    znMaterialExtend.setDefaultFlag("0");
                }
            }
        }else{//多产品类型
            //默认第一个 增加默认单位维护
            boolean flag = false;
            for(ZnMaterialExtend znMaterialExtend:znMaterialExtendList) {
                boolean isPrice = true;
                //商品采购价格为空的时候，期初库存中，如果有期初价格并且大于0的时候,就把第一个期初价格作为商品的采购价
                if(znMaterialExtend.getPurchaseDecimal()==null && znMaterial.getZnMaterialInitialStocks().size()>0){
                    for (ZnMaterialInitialStock znMaterialInitialStock:znMaterial.getZnMaterialInitialStocks()) {
                        if(znMaterialInitialStock.getPrice()!=null && znMaterialInitialStock.getPrice().longValue()>0 && isPrice){
                            znMaterialExtend.setPurchaseDecimal(znMaterialInitialStock.getPrice());
                            isPrice = false;
                        }
                    }
                }
                znMaterialExtend.setMaterialId(temp.getId());
                znMaterialExtend.setDeleteFlag("0");
                znMaterialExtend.setTenantId(znMaterial.getTenantId());
                if (StringUtils.isEmpty(znMaterialExtend.getDefaultFlag())) {
                    znMaterialExtend.setDefaultFlag("0");
                }
                if(!flag && znMaterialExtend.getCommodityUnit().equals(znMaterial.getUnit())){
                    znMaterialExtend.setDefaultFlag("1");
                    flag = true;
                }
                if(!znMaterialExtend.getCommodityUnit().equals(znMaterial.getUnit())){
                    znMaterialExtend.setCommodityUnit(znMaterial.getUnit());
                }
            }
        }
        System.out.println("1");
        System.out.println(JSON.toJSONString(znMaterialExtendList));
        //1原有的记录，进行更新
        for(ZnMaterialExtend znMaterialExtend:znMaterialExtendList){
            if(znMaterialExtend.getId()!=null){
                znMaterialExtendUpdate.add(znMaterialExtend);
                oldExtendIds.remove(znMaterialExtend.getId());
            }else{
               // 1判断原有删除的记录中匹配，是否跟现在的新的记录的单位一样的，将其状态变为正常
                boolean isFlag =  false;//是否匹配
                for (ZnMaterialExtend extend :temp.getZnMaterialExtendList()){
                    if(znMaterialExtend.getCommodityUnit().equals(extend.getCommodityUnit()) ){
//                        String defaultFlag = znMaterialExtend.getDefaultFlag();
                        BeanUtils.copyProperties(znMaterialExtend,extend);
                        extend.setDeleteFlag("0");
//                        extend.setDefaultFlag(defaultFlag);
                        znMaterialExtendUpdate.add(extend);
                        isFlag =  true;//匹配
                    }
                }
                if(!isFlag){//不匹配
                    znMaterialExtendInsert.add(znMaterialExtend);
                }
            }
        }
        System.out.println("2");
        System.out.println(JSON.toJSONString(znMaterialExtendInsert));
        System.out.println(oldExtendIds);
        if(!oldExtendIds.isEmpty()){//删除商品(伪删除)
            znMaterialMapper.deleteZnMaterialExtendByIds(oldExtendIds.toArray(new Long[oldExtendIds.size()]));
        }
        if (znMaterialExtendUpdate.size() > 0)//修改商品
        {
            znMaterialMapper.updatebatchZnMaterialExtend(znMaterialExtendUpdate);
        }

        if (znMaterialExtendInsert.size() > 0)//新增商品
        {
            znMaterialMapper.batchZnMaterialExtend(znMaterialExtendInsert);
        }
       // znMaterialMapper.deleteZnMaterialExtendByMaterialId(znMaterial.getId());
        //insertZnMaterialExtend(znMaterial);
       int count= znMaterialMapper.updateZnMaterial(znMaterial);
        List<ZnMaterialInitialStock>  znMaterialInitialStocks=  znMaterial.getZnMaterialInitialStocks();
        SysUser user=SecurityUtils.getLoginUser().getUser();
        if(znMaterialInitialStocks!=null){
            for(ZnMaterialInitialStock znMaterialInitialStock:znMaterialInitialStocks){
                boolean f=false;
                if(znMaterialInitialStock.getNumber()!=null&&znMaterialInitialStock.getNumber().longValue()>=0){//库存大于等于零在插入
                    f=true;
                }else if(znMaterialInitialStock.getLowSafeStock()!=null&&znMaterialInitialStock.getLowSafeStock().longValue()>=0){//库存大于零在插入
                    f=true;
                }else if(znMaterialInitialStock.getHighSafeStock()!=null&&znMaterialInitialStock.getHighSafeStock().longValue()>=0){//库存大于零在插入
                    f=true;
                }else if(znMaterialInitialStock.getPrice()!=null&&znMaterialInitialStock.getPrice().doubleValue()>=0){//库存大于零在插入
                    f=true;
                }
                BigDecimal initiaOldNumber=NumberUtil.toBigDecimal(0);
                if(f){
                    znMaterialInitialStock.setMaterialId(znMaterial.getId());
                    znMaterialInitialStock.setTenantId(user.getTenantId());
                    ZnMaterialInitialStock ZnMaterialInitialStockQuery=new ZnMaterialInitialStock();
                    ZnMaterialInitialStockQuery.setMaterialId(znMaterial.getId());
                    ZnMaterialInitialStockQuery.setTenantId(user.getTenantId());
                    ZnMaterialInitialStockQuery.setDepotId(znMaterialInitialStock.getDepotId());
                    List<ZnMaterialInitialStock> lists=znMaterialInitialStockMapper.selectZnMaterialInitialStockList(ZnMaterialInitialStockQuery);
                    if(lists.size()>0){//执行更新
                        ZnMaterialInitialStock  zupdate=lists.get(0);
                        initiaOldNumber=zupdate.getNumber();
                        zupdate.setHighSafeStock(znMaterialInitialStock.getHighSafeStock());
                        zupdate.setNumber(znMaterialInitialStock.getNumber());
                        zupdate.setLowSafeStock(znMaterialInitialStock.getLowSafeStock());
                        zupdate.setPrice(znMaterialInitialStock.getPrice());
                        znMaterialInitialStockMapper.updateZnMaterialInitialStock(zupdate);
                    }else{

                        znMaterialInitialStockMapper.insertZnMaterialInitialStock(znMaterialInitialStock);
                    }
                    /**
                     * 当前库存
                     */
                    ZnMaterialCurrentStock znMaterialCurrentStockQuery=new ZnMaterialCurrentStock();
                    znMaterialCurrentStockQuery.setTenantId(user.getTenantId());
                    znMaterialCurrentStockQuery.setMaterialId(znMaterial.getId());
                    znMaterialCurrentStockQuery.setDepotId(znMaterialInitialStock.getDepotId());
                    List<ZnMaterialCurrentStock> znMaterialCurrentStocks=znMaterialCurrentStockService.selectZnMaterialCurrentStockList(znMaterialCurrentStockQuery);
                    if(znMaterialCurrentStocks.size()>0){//执行更新
                        ZnMaterialCurrentStock currpdate=znMaterialCurrentStocks.get(0);
                        currpdate.setCurrentNumber(NumberUtil.add(NumberUtil.sub(currpdate.getCurrentNumber(),initiaOldNumber),znMaterialInitialStock.getNumber()));
                        znMaterialCurrentStockService.updateZnMaterialCurrentStock(currpdate);
                    }else{
                        ZnMaterialCurrentStock znMaterialCurrentStockInsert=new ZnMaterialCurrentStock();
                        znMaterialCurrentStockInsert.setCurrentNumber(znMaterialInitialStock.getNumber());
                        znMaterialCurrentStockInsert.setDeleteFlag("0");
                        znMaterialCurrentStockInsert.setDepotId(znMaterialInitialStock.getDepotId());
                        znMaterialCurrentStockInsert.setMaterialId(znMaterial.getId());
                        znMaterialCurrentStockInsert.setTenantId(user.getTenantId());
                        /*  znMaterialCurrentStocks.add(znMaterialCurrentStockInsert);*/
                        znMaterialCurrentStockService.insertZnMaterialCurrentStock(znMaterialCurrentStockInsert);
                    }
                }
            }
        }
            return count > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 批量删除产品
     * 
     * @param ids 需要删除的产品主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteZnMaterialByIds(Long[] ids)
    {
        znMaterialMapper.deleteZnMaterialExtendByMaterialIds(ids);
        return znMaterialMapper.deleteZnMaterialByIds(ids);
    }
    @Override
    public int handleEnableMaterial(Long[] ids, Integer enable) {
        Map map=new HashMap<>();
        map.put("id",ids);
        map.put("enable",enable);
        map.put("tenantId",SecurityUtils.getLoginUser().getUser().getTenantId());
        return znMaterialMapper.handleEnableMaterial(map);
    }

    @Override
    @DataScope(deptAlias = "m", userAlias = "m")
    public List<MaterialVo4Unit> getListWithStock(List<Long> depotList, List<Long> idList, String materialParam, Integer zeroStock, String column, String order) {
        Map<String, Object> params=new HashMap<>();
        params.put("tenantId",SecurityUtils.getTenantId());
        return znMaterialMapper.getListWithStock(depotList, idList, materialParam, zeroStock, column, order,params);
    }

    @Override
    public MaterialVo4Unit getTotalStockAndPrice(List<Long> depotList, List<Long> idList, String materialParam) {
        Map<String, Object> params=new HashMap<>();
        params.put("tenantId",SecurityUtils.getTenantId());
        return znMaterialMapper.getTotalStockAndPrice(depotList, idList, materialParam,params);
    }

    @Override
    public List<ZnMaterial> selectZnMaterialSelectList(ZnMaterial znMaterial) {
        znMaterial.setTenantId(SecurityUtils.getLoginUser().getUser().getTenantId());
        znMaterial.setDeleteFlag("0");
        List<ZnMaterial> list=  znMaterialMapper.selectZnMaterialSelectList(znMaterial);
//        for (ZnMaterial temp:list) {
//            BigDecimal currentNumberNew = temp.getCurrentNumber().divide(new BigDecimal(temp.getUnitRatio()),0,BigDecimal.ROUND_DOWN);
//            temp.setCurrentNumber(currentNumberNew);
//        }
        return list;
    }

    @Override
    public List<ZnMaterialExtend> getListByMIds(List<Long> idList) {
        List<ZnMaterialExtend> meList = null;
            Long [] idArray= StringUtil.listToLongArray(idList);
            if(idArray!=null && idArray.length>0) {
                meList = znMaterialMapper.getListByMId(idArray);
            }

        return meList;
    }

    @Override
    public ZnUnit findUnit(Long materialId) {
        ZnUnit unit = new ZnUnit();
            List<ZnUnit> list = znMaterialMapper.findUnitList(materialId);
            if(list!=null && list.size()>0) {
                unit = list.get(0);
            }

        return unit;
    }

    /**
     * 删除产品信息
     * 
     * @param id 产品主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteZnMaterialById(Long id)
    {
        znMaterialMapper.deleteZnMaterialExtendByMaterialId(id);
        return znMaterialMapper.deleteZnMaterialById(id);
    }

    @Override
    public String getMaxBarCode() {
        Long tenantId= SecurityUtils.getLoginUser().getUser().getTenantId();
        String maxBarCodeOld = znMaterialMapper.getMaxBarCode(tenantId);
        if(StringUtils.isNotEmpty(maxBarCodeOld)) {
            return Long.parseLong(maxBarCodeOld)+"";
        } else {
            return "1000";
        }
    }



    /**
     * 新增产品价格扩展信息
     * 
     * @param znMaterial 产品对象
     */
    public void insertZnMaterialExtend(ZnMaterial znMaterial)
    {
        List<ZnMaterialExtend> znMaterialExtendList = znMaterial.getZnMaterialExtendList();
        Long id = znMaterial.getId();
        if (StringUtils.isNotNull(znMaterialExtendList))
        {
            List<ZnMaterialExtend> list = new ArrayList<ZnMaterialExtend>();
            int index =0;
            for (ZnMaterialExtend znMaterialExtend : znMaterialExtendList)
            {
                boolean isPrice = true;
                //商品采购价格为空的时候，期初库存中，如果有期初价格并且大于0的时候,就把第一个期初价格作为商品的采购价
                if(znMaterialExtend.getPurchaseDecimal()==null && znMaterial.getZnMaterialInitialStocks().size()>0){
                    for (ZnMaterialInitialStock znMaterialInitialStock:znMaterial.getZnMaterialInitialStocks()) {
                        if(znMaterialInitialStock.getPrice()!=null && znMaterialInitialStock.getPrice().longValue()>0 && isPrice){
                            znMaterialExtend.setPurchaseDecimal(znMaterialInitialStock.getPrice());
                            isPrice = false;
                        }
                    }
                }
                if(index ==0){
                    znMaterialExtend.setCommodityUnit(znMaterial.getUnit());
                    znMaterialExtend.setDefaultFlag("1");
                }else{
                    znMaterialExtend.setDefaultFlag("0");
                }
                index++;
                znMaterialExtend.setDeleteFlag("0");
                znMaterialExtend.setCreateTime(new Date());
                znMaterialExtend.setCreateSerial(SecurityUtils.getUsername());
                znMaterialExtend.setMaterialId(id);

                list.add(znMaterialExtend);
            }
            if (list.size() > 0)
            {
                znMaterialMapper.batchZnMaterialExtend(list);
            }
        }
    }
}
